import json

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import transaction

from utils.ResponseResult import success_result_json, fail_result_json
from .models import BookTypeModel
from django.shortcuts import get_object_or_404


def query_book_type_list(request):
    json_data = json.loads(request.body)
    type_name = json_data.get("typeName", None)
    page_no = json_data.get("pageNo", 1)
    page_size = json_data.get("pageSize", 10)
    # 是否分页 默认开启
    isPage = json_data.get("isPage", True)
    print(f"参数： {type_name}, {page_no}, {page_size}, {isPage}")
    params = {}
    if type_name:
        params["type_name__contains"] = type_name
    typeList = BookTypeModel.objects.filter(**params)

    if isPage:
        paginator_types = Paginator(typeList, page_size)
        try:
            types = paginator_types.page(page_no)
        except PageNotAnInteger:
            types = paginator_types.page(1)
        except EmptyPage:
            types = paginator_types.page(paginator_types.num_pages)
        # 返回值处理方式一
        type_list = [
            {
                "typeId": t.type_id,
                "typeName": t.type_name,
                "typeCode": t.type_code
            }
            for t in types
        ]

        # 方式二
        # s_data = serialize('json', types)
        # r_data = json.loads(s_data)
        # # 方式三，普通for
        # print(f"数据：{r_data}")

        result = {
            "bookTypeList": type_list,
            "totals": paginator_types.count
        }

        return success_result_json(result)
    else:
        type_list = [
            {
                "typeId": t.type_id,
                "typeName": t.type_name,
                "typeCode": t.type_code
            }
            for t in typeList
        ]
        return success_result_json(type_list)


def add_book_type(request):
    json_param = json.loads(request.body)
    print(f"json_param: {json_param}")

    type_code = json_param.get("typeCode", None)
    type_name = json_param.get("typeName", None)
    if not type_code or not type_name:
        return fail_result_json(msg="类型编码、名称不能为空")

    try:
        # 保存方法一
        # type_info = BookTypeModel(type_code=type_code, type_name=type_name)
        # type_info.save()
        # 方法二
        book = BookTypeModel.objects.create(type_code=type_code, type_name=type_name)
        print(f"保存数据：{book}")
        return success_result_json(msg="类型保存成功")
    except Exception as e:
        return fail_result_json(msg=f"类型保存异常，{e},请联系管理员", code=500)


# 此处的参数名要和urls中的参数名一致
@transaction.atomic
def deleteBookType(request, typeId):
    # 开启事务
    sid = transaction.savepoint()
    try:
        print(f"删除类型id：{typeId}")

        # type_info = BookTypeModel.objects.get(type_id=typeId)
        type_info = get_object_or_404(BookTypeModel, type_id=typeId)
        if not type_info:
            return fail_result_json(msg="类型不存在")
        type_info.delete()

        # 提交事务
        transaction.savepoint_commit(sid)
        return success_result_json(msg="类型删除成功")
    except Exception as e:
        # 回滚
        transaction.savepoint_rollback(sid)
        return fail_result_json(msg=f"类型删除异常，{e},请联系管理员", code=500)


def updateBookType(request):
    try:
        with transaction.atomic():
            json_param = json.loads(request.body)
            print(f"json_param: {json_param}")
            type_id = json_param.get("typeId", None)
            type_code = json_param.get("typeCode", None)
            type_name = json_param.get("typeName", None)
            if not type_id or not type_code or not type_name:
                return fail_result_json(msg="书籍类型信息不能为空")
            type_info = BookTypeModel.objects.get(type_id=type_id)
            type_info.type_code = type_code
            type_info.type_name = type_name
            type_info.save()
            return success_result_json(msg="类型修改成功")
    except Exception as e:
        return fail_result_json(msg=f"类型修改异常，{e},请联系管理员", code=500)
